package org.chnxi.study.concurrent.abc.demo;

import java.util.concurrent.Semaphore;

/**
 * 使用Semaphore实现
 */
public class Demo4 {

    public static class SemaphoreABC{
        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(0);
        Semaphore c = new Semaphore(0);

        public void printA(){
            doPrint("A" , a , b);
        }

        public void printB(){
            doPrint("B" , b , c);
        }

        public void printC(){
            doPrint("C" , c , a);
        }

        /**
         *
         * @param content 需要输出的内容
         * @param cur 当前Semaphore的对象，需要获取到执行权限
         * @param next 对下一个要执行的Semaphore的对象释放一个执行权限
         */
        private void doPrint(String content , Semaphore cur , Semaphore next){
            try{
                cur.acquire();
                System.out.println(Thread.currentThread().getName()+":"+content);
                next.release();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SemaphoreABC abc = new SemaphoreABC();

        new Thread(()->{
            //while (true){
                abc.printA();
            //}
        }).start();
        new Thread(()->{
            //while (true){
                abc.printB();
            //}
        }).start();
        new Thread(()->{
            //while (true){
                abc.printC();
            //}
        }).start();
    }


}
